// pages/index/index.js
const app = getApp()

Page({
  data: {
    activeCategory: 0,
    caseList: [],
    banners: [
      'https://images.unsplash.com/photo-1497366754035-f200968a6e72?ixlib=rb-4.0.3&auto=format&fit=crop&w=1200&q=80',
      'https://images.unsplash.com/photo-1505373877841-8d25f7d46678?ixlib=rb-4.0.3&auto=format&fit=crop&w=1200&q=80',
      'https://images.unsplash.com/photo-1547658719-da2b51169166?ixlib=rb-4.0.3&auto=format&fit=crop&w=1200&q=80'
    ],
    filteredCategories: [
      { id: 1, name: '展馆设计' },
      { id: 2, name: '活动策划' },
      { id: 3, name: '平面设计' },
      { id: 5, name: '品牌设计' }
    ],
    page: 1,
    pageSize: 10,
    hasMore: true,
    isLoading: false,
    globalData: {
      categories: [
        { id: 1, name: '展馆设计' },
        { id: 2, name: '活动策划' },
        { id: 3, name: '平面设计' },
        { id: 5, name: '品牌设计' }
      ],
      cases: [
        // 原有案例数据...
      ],
      news: [
        // 原有新闻数据...
      ]
    }
  },
  
  onLoad: function() {
    wx.showLoading({ title: '加载中', mask: true });
    this.setData({
      caseList: [] // 初始化清空列表
    }, () => {
      this.loadCaseData();
    });
  },
  
  // 加载案例数据
  loadCaseData: function() {
    this.setData({ isLoading: true });
    
    const allCases = this.data.globalData.cases;
    const start = (this.data.page - 1) * this.data.pageSize;
    const end = start + this.data.pageSize;
    const newCases = allCases.slice(start, end);
    
    this.setData({
      caseList: [...this.data.caseList, ...newCases],
      hasMore: end < allCases.length,
      isLoading: false
    }, () => {
      wx.hideLoading();
      // 添加滚动修复
      if (this.data.page === 1) {
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 0
        });
      }
    });
  },
  
  // 分类切换处理
  switchCategory: function(e) {
    const categoryId = parseInt(e.currentTarget.dataset.id);
    this.setData({ 
      activeCategory: categoryId,
      caseList: [],
      page: 1,
      hasMore: true
    }, () => {
      wx.showLoading({ title: '加载中' });
      this.loadCaseData();
    });
  },
  
  // 获取分类名称
  getCategoryName: function(categoryId) {
    const category = this.data.filteredCategories.find(cat => cat.id === categoryId);
    return category ? category.name : '其他';
  },
  
  // 上拉加载更多
  onReachBottom: function() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.setData({ page: this.data.page + 1 }, () => {
        this.loadCaseData();
      });
    }
  },
  
  // 图片加载失败处理
  onImageError: function(e) {
    const caseId = e.currentTarget.dataset.id;
    const newList = this.data.caseList.map(item => {
      if (item.id === caseId) {
        return {...item, cover: '/images/default-cover.jpg'};
      }
      return item;
    });
    this.setData({ caseList: newList });
  }
});